// Package
/**
 * @author: byz08
 * @description:
 * @file: serve_pkg
 * @version: 1.0.0
 * @date: 2022/6/8 8:55
 */
package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)

const BUFFER_SIZE int = 4096

// Server
// @Description: 服务器对象
type Server struct {
	Ip   string
	Port int
	//在线用户列表
	OnlineMap map[string]*User
	mapLock   sync.RWMutex
	//消息广播Channel
	Message chan string
}

// NewServer
// @Description: 创建一个Server对象
// @param ip ip地址
// @param port 端口号
// @return *Server
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

// BroadCastToUSer
// @Description:
// @receiver this
// @param user
// @param msg
func (this *Server) BroadCastToUSer(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ": " + msg
	//发给channel
	this.Message <- sendMsg
}

func (this *Server) ListenMassage() {
	for {
		//阻塞读取数据
		msg := <-this.Message
		//遍历map
		this.mapLock.Lock()
		//fmt.Println("serverListen:" + msg)
		for _, user := range this.OnlineMap {
			user.Channel <- msg
		}
		this.mapLock.Unlock()
	}
}

// Handler
// @Description: 处理实际业务
// @receiver this
// @param conn
func (this *Server) Handler(conn net.Conn) {
	//处理连接业务
	//fmt.Println("serve_pkg connect success!")
	//用户上线，创建连接对象
	user := NewUser(conn, this)
	//1.处理用户上线业务
	user.Online()
	//设置在线标志
	isAlive := make(chan bool)
	//2.接受客户端传递的消息
	go func() {
		buf := make([]byte, BUFFER_SIZE)
		//循环监听
		for {
			n, err := conn.Read(buf)
			//正常下线(长度为0)
			if n == 0 {
				user.OffLine()
				return
			}
			//处理错误
			if err != nil && err != io.EOF {
				fmt.Println("Conn read error: ", err)
				return
			}
			//3.提取用户消息，去除\n 加入广播
			msg := string(buf[:n-1])
			//fmt.Println("ready to send")
			//发送消息
			user.DoMessage(msg)
			//fmt.Println("after  sent")
			//设置用户活跃状态
			isAlive <- true
		}
	}()
	//循环查看用户活跃状态
	for {
		//利用select阻塞处理
		select {
		//设置定时器
		case <-isAlive:
			//重置计时器2
		case <-time.After(time.Second * 60):
			//发送消息提示
			user.SendMsgToThisUser("[system]: your had long time to send msg , you will be block !!!")
			user.SendMsgToThisUser("[system]:block")
			//强制关闭通信管道
			close(user.Channel)
			//关闭连接
			err := conn.Close()
			if err != nil {
				fmt.Println("--system.log: ", err)
				return
			}
			//清除登陆用户信息 空指针会被垃圾回收，这里不一定需要处理删除map 读不到数据执行offline消除用户
			//退出当前GO程(handler)
			//runtime.Goexit()
			return
		}
	}

}

func (this *Server) Start() {
	//开始socket
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("net listener has error : ", err)
		return
	}
	//监听服务器上是否需要发送消息给全部用户 服务器的channel不为空
	go this.ListenMassage()
	//close服务端监听的 socket
	defer listener.Close()

	//循环一直监听客户端是否连接
	for {
		conn, err := listener.Accept()
		//accept
		if err != nil {
			fmt.Println("listener accept error : ", err)
			continue
		}
		//do handle 异步处理一个业务
		//fmt.Println("accept coon !")
		go this.Handler(conn)
	}

}
